package config

import (
	"acs/taskprocess/storage"
	"os"

	"github.com/BurntSushi/toml"
	flags "github.com/jessevdk/go-flags"
)

const (
	DefaultMaxAppConnections = int32(20000)
)

var (
	Conf       *Config
	ConfigFile string
)

type Config struct {
	AppConfServerBind            string         `toml:"app_conf_server_bind"`
	WnetAddress                  string         `toml:"wnet_address"`
	ControlServerBind            string         `toml:"control_server_bind"`
	DataEncryptIV                string         `toml:"data_encrypt_iv"`
	DataEncryptKey               string         `toml:"data_encrypt_key"`
	EventBrokerEndpoints         []string       `toml:"event_broker_endpoints"`
	EventBrokerAuthinfo          string         `toml:"event_broker_authinfo"`
	TaskServerQueueServerLookupd []string       `toml:"task_queue_server_lookupd"`
	TaskQueueTopic               string         `toml:"task_queue_topic"`
	TaskQueueChannel             string         `toml:"task_queue_channel"`
	StorageMgo                   storage.Config `toml:"storage_mgo"`
	CtrlEventKey                 string         `toml:"ctrl_event_key"`
	EventBrokerHeartBeatTTL      int64          `toml:"event_broker_heartbeat_ttl"`
	NodesMonitorDir              string         `toml:"nodes_monitor_dir"`
	ClientListShard              int            `toml:"client_list_shard"`
	MaxProtoSize                 uint32         `toml:"max_proto_size"`
	HeartBeatTimeout             int64          `toml:"heart_beat_timeout"`
	MaxReqRespTimeout            uint32         `toml:"max_request_response_timeout"`
	MaxAppConnections            int32          `toml:"max_app_connections"`
	ClientHandshakeTimeout       uint32         `toml:"client_handshake_timeout"`
	LogLevels                    string         `toml:"log_level"`
	EventExpiration              int64          `toml:"event_expiration"`
}

func InitConfig() *Config {
	var argOpts struct {
		ConfigFile string `short:"c" long:"config-file" description:"set config file path" default:"./comet/config.toml" value-name:"FILE"`
		ShowHelp   bool   `short:"h" long:"help" description:"show this help message"`
	}
	argParser := flags.NewNamedParser("ACS", flags.IgnoreUnknown|flags.PrintErrors|flags.PassDoubleDash)
	_, err := argParser.AddGroup("configs", "", &argOpts)
	if err != nil {
		panic(err)
	}
	_, err = argParser.Parse()
	if err != nil {
		panic(err)
	}
	if argOpts.ShowHelp {
		argParser.WriteHelp(os.Stdout)
		os.Exit(0)
	}
	ConfigFile = argOpts.ConfigFile

	config := new(Config)
	if _, err := toml.DecodeFile(ConfigFile, config); err != nil {
		panic(err)
	}
	if config.HeartBeatTimeout <= 0 {
		config.HeartBeatTimeout = 10000
	}
	if config.MaxProtoSize <= 0 {
		config.MaxProtoSize = 1024 * 1024
	}

	if config.MaxReqRespTimeout <= 0 {
		config.MaxReqRespTimeout = 8000
	}

	if config.MaxAppConnections <= 0 {
		config.MaxAppConnections = DefaultMaxAppConnections
	}
	Conf = config
	return config
}
